﻿using System.Collections.Generic;
using UnityEngine;

public class PrefabSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject m_Prefab;

    private List<GameObject> m_Instances = new List<GameObject>();
    private List<GameObject> m_ResultObjects = new List<GameObject>();

    private void CheckOriginInstances()
    {
        if (m_Instances.Count == 0 && transform.childCount != 0)
        {
            for (int i = 0; i < transform.childCount; i++)
            {
                var go = transform.GetChild(i).gameObject;
                if (go.name.Contains(m_Prefab.name))
                {
                    m_Instances.Add(go);
                }
            }
        }
    }

    public List<GameObject> Spawn(int count)
    {
        CheckOriginInstances();
        m_Instances.ForEach(ins => ins.SetActive(false));
        if (m_Instances.Count < count)
        {
            int needCount = count - m_Instances.Count;
            for (int i = 0; i < needCount; i++)
            {
                var instance = Instantiate(m_Prefab, transform);
                instance.SetActive(false);
                m_Instances.Add(instance);
            }
        }
        m_ResultObjects.Clear();
        for (int i = 0; i < count; i++)
        {
            var instance = m_Instances[i];
            instance.SetActive(true);
            m_ResultObjects.Add(instance);
        }
        return m_ResultObjects;
    }

    public void Spawn<T>(int count, List<T> results) where T : UnityEngine.Object
    {
        if (results == null)
        {
            Debug.LogError($"Prefab 生成失败：目标数组为 null");
            return;
        }
        results.Clear();
        var resultObjects = Spawn(count);
        foreach (var resultObj in resultObjects)
        {
            var result = resultObj.GetComponent<T>();
            if (result == null)
            {
                Debug.LogError($"Prefab 生成失败：生成了空对象");
                return;
            }
            results.Add(result);
        }
    }

    public void DespawnAll()
    {
        CheckOriginInstances();
        m_Instances.ForEach(ins => ins.SetActive(false));
        m_ResultObjects.Clear();
    }
}